package com.ruoyi.web.controller.wechat;

import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.enums.UserTypeEnum;
import com.ruoyi.common.enums.WeChatUserVerifyStatus;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.manager.AsyncManager;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.domain.vo.VerifyWeChatUserVo;
import com.ruoyi.system.domain.vo.WeChatConsumerVo;
import com.ruoyi.system.domain.vo.WeChatEmployeeVo;
import com.ruoyi.system.domain.vo.WeChatVo;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.system.service.IWeChatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 微信接口
 * @author lisongtao
 * @date 2023/5/12 11:17
 */
@RestController
@RequestMapping("/weChat")
public class WeChatController {


    @Autowired
    private IWeChatService weChatService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private SysPermissionService permissionService;

    /**
     * 验证微信用户是否存在
     */
    @Anonymous
    @PostMapping("/verifyWeChatUser")
    public AjaxResult verifyWeChatUser(@RequestBody @Validated WeChatVo weChatVo) {
        AjaxResult result = AjaxResult.success();
        // 访问微信获取当前人的openId
        String userType = weChatVo.getUserType();
        UserTypeEnum userTypeEnum = UserTypeEnum.getUserTypeEnum(userType);
        if (userTypeEnum == null) {
            throw new ServiceException("用户类型不存在！");
        }
        String publicOpenId = weChatService.weChatLogin(weChatVo);
        VerifyWeChatUserVo verifyWeChatUserVo = userService.verifyWeChatUserExists(publicOpenId, userType);
        WeChatUserVerifyStatus verifyStatus = verifyWeChatUserVo.getVerifyStatus();
        result.put("verifyStatus", verifyStatus);
        result.put("publicOpenId", publicOpenId);
        if (WeChatUserVerifyStatus.EXIST.equals(verifyStatus)) {
            SysUser sysUser = verifyWeChatUserVo.getSysUser();
            // 完成登录
            // 生成用户信息token
            LoginUser loginUser = new LoginUser(sysUser.getUserId(), sysUser.getDeptId(), sysUser, permissionService.getMenuPermission(sysUser));
            result.put("token", tokenService.createToken(loginUser));
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(sysUser.getUserName(), Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        }
        return result;
    }

    /**
     * 员工微信端绑定校验
     */
    @Anonymous
    @PostMapping("/employeeBindingVerify")
    public AjaxResult employeeBindingVerify(@RequestBody @Validated WeChatEmployeeVo weChatEmployeeVo) {
        return AjaxResult.success(userService.employeeBindingVerify(weChatEmployeeVo));
    }


    /**
     * 供热用户绑定操作
     */
    @Anonymous
    @PostMapping("/consumerBindingOperation")
    public AjaxResult consumerBindingOperation(@RequestBody @Validated WeChatConsumerVo weChatConsumerVo) {
        SysUser sysUser = userService.consumerBindingOperation(weChatConsumerVo);
        return createToken(sysUser);
    }


    /**
     * 员工微信绑定操作
     */
    @Anonymous
    @PostMapping("/employeeBindingOperation")
    public AjaxResult employeeBindingOperation(@RequestBody @Validated WeChatEmployeeVo weChatEmployeeVo) {
        SysUser sysUser = userService.employeeBindingOperation(weChatEmployeeVo);
        return createToken(sysUser);
    }


    private AjaxResult createToken(SysUser sysUser) {
        AjaxResult result = AjaxResult.success();
        Assert.notNull(sysUser, "用户不能为空！");
        //TODO 记录日志操作
        String userName = sysUser.getUserName();
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(userName, Constants.REGISTER, MessageUtils.message("user.register.success")));
        // 生成用户信息token
        LoginUser loginUser = new LoginUser(sysUser.getUserId(), sysUser.getDeptId(), sysUser, permissionService.getMenuPermission(sysUser));
        result.put("token", tokenService.createToken(loginUser));
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(userName, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        return result;
    }

    /**
     * 取消微信关联
     * 内管和微信端均调用此方法
     */
    @Log(title = "用户取消微信关联", businessType = BusinessType.DELETE)
    @PostMapping("/cancelHandleWeChat")
    public AjaxResult cancelHandleWeChat() {
        Long userId = SecurityUtils.getUserId();
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        userService.cancelHandleWeChat(sysUser);
        return AjaxResult.success();
    }


}
